<?php
/**
 * AJAX Handler for Users: Add - Add a user if params are met, send feedback through ajax up to caller
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    require_once('../../SiteIncludes.GLOBAL.php');
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	$gVAR['e'] = '404';
	require_once('error_handler.php');
    }
    $_LIBDEBUG->silence();
    
    $return_head = <<<EOHEAD
	<!DOCTYPE html>
	    <html>
	    <head><title></title></head>
	    <body>
		<script type="text/javascript">
EOHEAD;
    $return_nok = 'parent.EDJXConfirmer.show_nok();';
    $return_body = $return_nok.' parent.NewUser.SubmitCallback(false, \'<b>Unknown Error Occured</b>.<br /><i>Please try again later</i>\');';
    $return_ok = 'parent.EDJXConfirmer.show_ok();';
    $return_foot = <<<EOFOOT
		</script>
	    </body>
	</html>
EOFOOT;
    
    if(isset($pVAR['ib_text_nametocheck']) === true && isset($pVAR['ib_text_emailtocheck']) === true && isset($pVAR['ib_text_password_password']) === true && isset($pVAR['ib_text_password_confirm']) ===true && isset($pVAR['ib_submitbutton']) ===true) {
	
	// ------------- Enforce Rules on Username - must have one letter
	$match = preg_match('/^([a-z0-9_]+)?([a-z]+)([a-z0-9_]+)?$/i', $pVAR['ib_text_nametocheck']);
	if($match) {
	    try {
		// Try and get the user, if we throw no exception. Username is in use.
		$user =& $UserStash->get($pVAR['ib_text_nametocheck']);
		$return_body = <<<EOBODY
		    $return_nok
		    parent.NewUser.SubmitCallback(false, 'Sorry, that username is taken.');
		    parent.NewUser.img_username_status.src = '/img/not_ok.png';
		    parent.NewUser.updateSubmitButton();
EOBODY;
	    } catch(InvalidUserException $e) {
		// Username is free. Check the Email Address is valid.
		if(filter_var($pVAR['ib_text_emailtocheck'], FILTER_VALIDATE_EMAIL) === false) {
		    // Email is invalid
		    $return_body = <<<EOBODY
			$return_nok
			parent.NewUser.SubmitCallback(false, 'Sorry, that email does not seem to be valid.');
			parent.NewUser.img_email_status.src = '/img/not_ok.png';
			parent.NewUser.updateSubmitButton();
EOBODY;
		} else {
		    // Check passwords are equal
		    if(strcmp($pVAR['ib_text_password_confirm'], $pVAR['ib_text_password_password']) !== 0) {
			// Invalid Passwords - they do not match
			$return_body = <<<EOBODY
			    $return_nok
			    parent.NewUser.SubmitCallback(false, 'Your passwords do not match.');
			    parent.NewUser.img_password_status.src = '/img/not_ok.png';
			    parent.NewUser.updateSubmitButton();
EOBODY;
		    } else {
			// Passwords match - are they above minimum length and below maximum?
			if(strlen($pVAR['ib_text_password_password']) < 5) {
			    $return_body = <<<EOBODY
				$return_nok
				parent.NewUser.SubmitCallback(false, 'Your password is too short. 5 Characters Minimum.');
				parent.NewUser.img_password_status.src = '/img/not_ok.png';
				parent.NewUser.updateSubmitButton();
EOBODY;
			} elseif(strlen($pVAR['ib_text_password_password']) > 26) {
			    $return_body = <<<EOBODY
				$return_nok
				parent.NewUser.SubmitCallback(false, 'Your password is too long. 26 Characters Maximum.');
				parent.NewUser.img_password_status.src = '/img/not_ok.png';
				parent.NewUser.updateSubmitButton();
EOBODY;
			} else {
			    // Everything is OK. Commit to database
			    $safe_username = $sql_conx->real_escape_string($pVAR['ib_text_nametocheck']);
			    $safe_email = $sql_conx->real_escape_string($pVAR['ib_text_emailtocheck']);
			    $now = time();
			    $safe_password = Password::hashPassword($pVAR['ib_text_password_password'], $now);
			    $safe_now = $sql_conx->real_escape_string($now);
			    $query = $sql_conx->query("INSERT INTO  `emde`.`users` ( `uid` , `username` , `password` , `email` , `priv_adm` , `profile_icon`, `signup_time` ) VALUES ( NULL ,  '{$safe_username}',  '{$safe_password}',  '{$safe_email}',  '0',  '', '{$safe_now}');");
			    if($sql_conx->affected_rows === 0) {
				header("HTTP/1.1 500 Internal Server Error");
				$return_body = <<<EOBODY
				$return_nok
				parent.NewUser.SubmitCallback(false, '<b>Error 500 : Internal Server Error</b>.<br /><i>Please try again later</i>.');
EOBODY;
			    } else {
				$return_body = <<<EOBODY
				$return_ok
				parent.NewUser.SubmitCallback(true, '');
EOBODY;
			    }
			}
		    }
		}
	    }
	} else {
	    // The form was incorrectly filled out.
	    $return_body = <<<EOBODY
		$return_nok
		parent.NewUser.SubmitCallback(false, 'Username should have at least one letter.');
EOBODY;
	}
    } else {
	$return_body = <<<EOBODY
	    $return_nok
	    parent.NewUser.SubmitCallback(false, 'Please fill out the entire form.');
EOBODY;
    }
    
    
    echo $return_head.$return_body.$return_foot;
?>
